# Display data distribution

library(ggplot2)

# One-dimension
# Histogram----
# >> geom_boxplot = stat_boxplot + geom_boxplot
depth_dist <- ggplot(diamonds, aes(depth)) + xlim(58, 68)
depth_dist + geom_histogram(aes(y = ..density..), binwidth = 0.1) +
  facet_grid(cut ~ .)

depth_dist + geom_histogram(aes(fill = cut), binwidth = 0.1, position = "fill")

depth_dist + geom_freqpoly(aes(y = ..density.., colour = cut), binwidth = 0.1)

# Boxplot----
library(plyr)

# qplot(cut, depth, data = diamonds, geom = 'boxplot')
ggplot(diamonds, aes(cut, depth)) + geom_boxplot()

# qplot(carat, depth, data = diamonds, geom = "boxplot",
#       group = round_any(carat, 0.1, floor), xlim = c(0, 3))
ggplot(diamonds) + 
  geom_boxplot(aes(carat, depth, group = round_any(carat, 0.1, floor))) +
  xlim(0, 3)

# Jitter----
# >> geom_jitter = position_jitter + geom_point
# qplot(class, cty, data = mpg, geom = "jitter")
ggplot(mpg, aes(class, cty)) + geom_jitter()

ggplot(mpg, aes(class, drv)) + geom_jitter()

# Density----
# >> geom_density = stat_density + geom_area
# qplot(depth, data = diamonds, geom = "density", xlim = c(54, 70))
ggplot(diamonds) + geom_density(aes(depth)) + xlim(54, 70)

# qplot(depth, data = diamonds, geom = "density", xlim = c(54, 70),
#       fill = cut, alpha = I(0.2))
ggplot(diamonds) + geom_density(aes(depth, fill = cut), alpha = I(0.2)) + xlim(54, 70)

# Two-dimension
df <- data.frame(x = rnorm(2000), y = rnorm(2000))
norm <- ggplot(df, aes(x, y))
norm + geom_point()
norm + geom_point(shape = 1)
norm + geom_point(shape = ".")

norm + geom_point(colour = "black", alpha = 1/3)
norm + geom_point(colour = "black", alpha = 1/5)
norm + geom_point(colour = "black", alpha = 1/10)

td <- ggplot(diamonds, aes(table, depth)) + xlim(50, 70) + ylim(50, 70)
td + geom_point()
td + geom_jitter()
jit <- position_jitter(width = 0.5)
td + geom_jitter(position = jit)
td + geom_jitter(position = jit, colour = "black", alpha = 1/10)
td + geom_jitter(position = jit, colour = "black", alpha = 1/50)
td + geom_jitter(position = jit, colour = "black", alpha = 1/200)

library(hexbin)
d <- ggplot(diamonds, aes(carat, price)) + xlim(1, 3) + 
  theme(legend.position = "none")
d + stat_bin2d()
d + stat_bin2d(bins = 10)
d + stat_bin2d(binwidth = c(0.02, 200))

d + stat_binhex()
d + stat_binhex(bins = 10)
d + stat_binhex(binwidth = c(0.02, 200))

d <- ggplot(diamonds, aes(carat, price)) + xlim(1, 3) +
  theme(legend.position = "none")
d + geom_point() + geom_density2d()
d + stat_density2d(geom = "point", aes(size = ..density..), contour = FALSE) +
  scale_size_area()
d + stat_density2d(geom = "tile", aes(fill = ..density..), coutour = FALSE)
last_plot() + scale_fill_gradient(limits = c(1e-5, 8e-4))
